package mwa.cs.cr.ctrl;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import mwa.cs.dao.CustomerHistoryLogDAO;
import mwa.cs.dao.SMErrorLogDAO;
import mwa.cs.dao.UserLoginDAO;
import mwa.cs.database.Database;
import mwa.cs.util.JDate;

/**
 * Servlet implementation class CS22001Srvl
 */
public class CS22001Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private int vnSiteId;
	private int vnUserId;
	private String vaUrlAddress;
	private String vaAgentBrowser;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CS22001Srvl() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	vnSiteId = Integer.parseInt(request.getSession().getAttribute("site_id").toString());
		vnUserId = Integer.parseInt(request.getSession().getAttribute("user_id").toString());
    	vaUrlAddress = request.getParameter("url_address");
		vaAgentBrowser = request.getParameter("agent_browser");
		if (request.getParameter("process_type").equals("gotoShowHistory")) {
			showHistoryData(request, response);
			return;
		}
		else if (request.getParameter("process_type").equals("getDataTable")) {
			getDataTable(request, response);
			return;
		}
		
    }

    private void showHistoryData(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String vaCustomerAccount = request.getParameter("customer_account");
    	Database db = new Database();
		try {
			// set account and forward to cs0202001.jsp
			request.setAttribute("account", vaCustomerAccount);
			RequestDispatcher voRequestDispatcher = request.getRequestDispatcher("CS22001.jsp");
			voRequestDispatcher.forward(request, response);
			return;
		} catch (Exception e) {
			SMErrorLogDAO.getInstance().addLog(0, "CS22000", JDate.getDate(), JDate.getTime(),vnUserId, "CS22001Srvl", e.getMessage(),vaUrlAddress, vaAgentBrowser);
			RequestDispatcher voRequestDispatcher = request.getRequestDispatcher("CS22000.jsp");
			voRequestDispatcher.forward(request, response);
		} finally {
			db.close();
		}
    }
    
    @SuppressWarnings("unchecked")
    private void getDataTable (HttpServletRequest request, HttpServletResponse response) throws IOException {
    	String vaAccount = request.getParameter("account");
		// columns for sorting data
	    int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
	    int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
	    String vaDraw = request.getParameter("sEcho");	    
	    String vaSortDirection = request.getParameter("sSortDir_0"); // asc, desc

	    // get data from database
	    int vnTotal = 0;
	    int vnTotalAfterFilter = 0;
	    List<Map<String, Object>> voResult = null;
	    Database db = new Database();
	    try {
	    	CustomerHistoryLogDAO voCustomerHistoryLogManagement = new CustomerHistoryLogDAO(db);
	    	vnTotal = voCustomerHistoryLogManagement.getAllCountCustomerLogByAccount(vnSiteId, vaAccount);
	    	if (vnAmount == -1) {
	    		voResult = voCustomerHistoryLogManagement.findAllCustomerLog(vnSiteId, vaAccount, vaSortDirection);
	    		vnTotalAfterFilter = vnTotal;
	    	} else {
	    		voResult = voCustomerHistoryLogManagement.findCustomerLogToTable(vnSiteId, vaAccount, 
	    				vaSortDirection, vnStart, vnStart + vnAmount);
	    		vnTotalAfterFilter = vnTotal;
	    	}
	    } finally {
	    	db.close();
	    }
	    // prepare data to show in dataTable
	    PrintWriter voOut = response.getWriter();
	    // set sequence
	    int[] vnSequence = new int[voResult.size()];
	    for (int i = 1; i <= voResult.size(); i++)
    		vnSequence[i - 1] = i + vnStart;
	    Database db2 = new Database();
	    try {
	    	UserLoginDAO voUserLogin = new UserLoginDAO(db2);
	    	JSONObject voObject = new JSONObject();
		    JSONArray voListData = new JSONArray();
		    for (int i = 0; i < voResult.size(); i++) {
		    	Map<String, Object> voTmp = voResult.get(i);
				JSONArray voArray = new JSONArray();
				// 1. sequence
				voArray.add(vnSequence[i]);
				String vaTDate = JDate.getMonthNameByDate((String) voTmp.get("TRANSACTION_DATE"));
				if (vaTDate == null) vaTDate = "";
				String vaTTime = JDate.showTime((String) voTmp.get("TRANSACTION_TIME"));
				if (vaTTime == null) vaTTime = "";
				// 2. Date and Time
				voArray.add(vaTDate + " " + vaTTime);
				// 3. Type
				voArray.add((String) voTmp.get("TRANSACTION_TYPE"));
				// 4. old description
	            voArray.add((String) voTmp.get("OLD_DESCRIPTION"));
	            // 5. new description
	            voArray.add((String) voTmp.get("NEW_DESCRIPTION"));
	            // 6. modify
	            String vaModifyBy = ((BigDecimal) voTmp.get("MODIFY_BY")).toString();
				String vaName = voUserLogin.findNameByUserId(vnSiteId, Integer.parseInt(vaModifyBy));
				voArray.add(vaName);
				// adding array data into list
	            voListData.add(voArray);
		    }
		    voObject.put("sEcho", Integer.parseInt(vaDraw));
		    voObject.put("iTotalRecords", vnTotal);
	        voObject.put("iTotalDisplayRecords", vnTotalAfterFilter);
	        voObject.put("aaData", voListData);
	        voOut.print(voObject.toJSONString());
	    } finally {
	    	db2.close();
			voOut.close();
		}
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		processRequest(request, response);
	}

}
